#include "SerialWrapper.h"
#include <sstream>

std::string SerialWrapper::COM[]= {"","/dev/ttyO1","/dev/ttyO2","","/dev/ttyO4"};
bool SerialWrapper::COM_AVAILABLE[]= {false,true,true,false,true};


SerialWrapper::SerialWrapper(short ComNum, int BaudRate):
m_ComNum(ComNum)
{
	if(!SerialWrapper::COM_AVAILABLE[m_ComNum])
		return;

	SerialWrapper::COM_AVAILABLE[m_ComNum] = false;

	if(m_ComNum == 1)
	{
		//Set rx pin in mode 0
		std::stringstream RxFileName;
		RxFileName<< "/sys/kernel/debug/omap_mux/uart1_rxd";
		int RxFd = open(RxFileName.str().c_str(), O_WRONLY);
		//write(RxFd , "20", 2);
		write(RxFd , "0x8020", 6);
		close(RxFd);

		//Set tx pin in mode 0
		std::stringstream TxFileName;
		TxFileName<< "/sys/kernel/debug/omap_mux/uart1_txd";
		int TxFd = open(TxFileName.str().c_str(), O_WRONLY);
		write(TxFd , "0x8000", 6);
		close(TxFd );
	}
	else if(m_ComNum == 2)
	{
		//Set rx pin in mode 0
		std::stringstream RxFileName;
		RxFileName<< "/sys/kernel/debug/omap_mux/spi0_sclk";
		int RxFd = open(RxFileName.str().c_str(), O_WRONLY);
		//write(RxFd , "20", 2);
		write(RxFd , "0x8021", 6);
		close(RxFd);

		//Set tx pin in mode 0
		std::stringstream TxFileName;
		TxFileName<< "/sys/kernel/debug/omap_mux/spi0_d0";
		int TxFd = open(TxFileName.str().c_str(), O_WRONLY);
		write(TxFd , "0x8001", 6);
		close(TxFd );
	}

	m_HandleOpened = false;

	m_Handle = open(SerialWrapper::COM[m_ComNum].c_str(), O_RDWR | O_NOCTTY | O_NDELAY);

	if(-1 == m_Handle)
	{
		std::cout << "Open << TtyFileName << failed!" << std::endl;
		m_HandleOpened = false;
		return;
	}

	struct termios options;

	fcntl(m_Handle, F_SETFL, FNDELAY);

	tcgetattr(m_Handle, &options);
	
	//cfsetispeed(&options, B115200);

	cfsetispeed(&options, BaudRate);
	cfsetospeed(&options, BaudRate);
	
	options.c_iflag = 0;
	options.c_oflag = 0;

	options.c_cflag |= (CLOCAL | CREAD);
	options.c_cflag &= ~PARENB;
	options.c_cflag &= ~CSTOPB;
	options.c_cflag &= ~CSIZE;
	options.c_cflag |= CS8;
	options.c_cflag &= ~CRTSCTS; 
	
	//options.c_lflag &= ~(ICANON | ECHO | ISIG);

	if(-1 == tcsetattr(m_Handle, TCSANOW, &options))
	{
		std::cout << "tcsetattr call failed!" << std::endl;
		m_HandleOpened = false;
		return;
	}

	m_HandleOpened = true;
}

SerialWrapper::~SerialWrapper()
{
	SerialWrapper::COM_AVAILABLE[m_ComNum] = true;
	close(m_Handle);
	m_HandleOpened = false;
}
